/**
 * @see https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * @description 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  let i = 0;
  let l = s.length - 1;
  let substrMap = {};
  let substrArr = [];
  let max = 0;
  while(i <= l) {
    let code = s.charAt(i);
    // 没有遇到重复串
    if(typeof substrMap[code] === 'undefined') {
      substrMap[code] = i;
      substrArr.push(code);
      i++;
    } else {
      // 遇到重复的串，找到其位置
      max = Math.max(substrArr.length, max);
      // 回到之前的位置重新匹配
      i = substrMap[code] + 1;
      substrMap = {};
      substrArr = [];
    }
  }
  max = Math.max(substrArr.length, max);
  return max
};
// console.time('begin')
// console.log(lengthOfLongestSubstring2('abcabcbb'));
// console.timeEnd('begin');
// console.log(lengthOfLongestSubstring('abcbc'));

var lengthOfLongestSubstring2 = function(s) {
  let arr = [];
  let max = 0;
  for(let item of s){
    if(arr.includes(item)){
      let index = arr.indexOf(item);
      arr.splice(0, index + 1);
    }
    arr.push(item);
    max = max > arr.length ? max : arr.length;
  }
  return max;
};

console.time('begin')
console.log(lengthOfLongestSubstring2('abcabcdtd'));
console.timeEnd('begin');